//js时间格式化;
var monitorpage=0;
Date.prototype.format = function(format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

$(function () {
    $.fn.datetimepicker.dates['ch'] = {
        days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
        daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
        months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        today: "今天",
        suffix: [],
        meridiem: ["上午", "下午"]
    };

    $('#datetimepicker_b').datetimepicker({
        //bootcssVer:3,
        format: 'yyyy-mm-dd hh:ii:00',
        startDate:'2000-01-01',
        autoclose:true,
        todayBtn:'linked',
        todayHighlight:true,
        language:'ch'
    });
    $('#datetimepicker_e').datetimepicker({
        //bootcssVer:3,
        format: 'yyyy-mm-dd hh:ii:00',
        startDate:'2000-01-01',
        autoclose:true,
        todayBtn:'linked',
        todayHighlight:true,
        language:'ch'
    });

    var date=new Date();
    $('#accepttime_e').val(date.format("yyyy-MM-dd hh:mm:ss"));
    //date.setHours(date.getHours()-1);
    var datee=new Date(date.getTime() - 24*60*60*1000);
    $('#accepttime_b').val(datee.format("yyyy-MM-dd hh:mm:ss"));

    /**
     * 初始化应用列表
     */
    function initAppList() {
        $.ajax({
            type: 'GET',
            url: "/app/list",
            dataType: 'json',
            cache: false,
            async: true,
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                // 表格数据
                $('#appName_s option').remove();
                $('#appName_s').append("<option value=''>请选择应用</option>");
                data.forEach(function (app) {
                    $('#appName_s').append("<option value='"+app.appName+"'>"+app.appName+"</option>");
                })
            },
            error: function (data) {
            }
        });
    }

    /**
     * 校验查询条件
     * @returns {boolean}
     */
    function validCheck(){
        var acceptBeginTime=$("#accepttime_b").val();
        var acceptEndTime=$("#accepttime_e").val();
        var appName = $("#appName_s option:selected").val();
        if(appName==null || appName==''){
            alert("应用名称不能为空");
            return false;
        }

        if(acceptBeginTime==null || acceptEndTime==null){
            alert("查询开始时间和结束时间不能为空");
            return false;
        }

        var ds=new Date(acceptBeginTime.replace("-","/"));
        var de=new Date(acceptEndTime.replace("-","/"));
        if(de.getTime()<ds.getTime()){
            alert("结束时间不能小于开始时间");
            return false;
        }
        return true;
    }

    /**
     * 根据条件查询日志
     */
    $("#search-log").click(function () {
        if(!validCheck()){
            return;
        }
        var acceptBeginTime=$("#accepttime_b").val();
        var acceptEndTime=$("#accepttime_e").val();
        var appName = $("#appName_s option:selected").val();
        var username = $("#dbuser_s").val();

        monitorpage=0;
        loadLogTable(acceptBeginTime,acceptEndTime,appName,username,monitorpage);
        $("#currentpage").html("当前页：1");
    })

    /**
     * 上一页，下一页
     */
    $('.page-link').click(function () {
        if(!validCheck()){
            return;
        }

        var $this = $(this);
        var acceptBeginTime=$("#accepttime_b").val();
        var acceptEndTime=$("#accepttime_e").val();
        var appName=$("#appName_s option:selected").val();
        var username = $("#dbuser_s").val();

        var navType = $this.data("paging-type");
        if (navType && navType === "prev") {
            if (monitorpage != 0) {
                monitorpage--;
            }
            loadLogTable(acceptBeginTime,acceptEndTime,appName,username, monitorpage);
            $("#firstpage").parent().removeClass("active");
            $("#currentpage").parent().removeClass("active");
            $("#currentpage").parent().addClass("active");
        } else if (navType && navType === "next") {
            monitorpage++;
            loadLogTable(acceptBeginTime,acceptEndTime,appName,username, monitorpage);
            $("#firstpage").parent().removeClass("active");
            $("#currentpage").parent().removeClass("active");
            $("#currentpage").parent().addClass("active");
        } else if (navType && navType === "first") {
            monitorpage = 0;
            loadLogTable(acceptBeginTime,acceptEndTime,appName,username, monitorpage);
            $("#firstpage").parent().removeClass("active");
            $("#firstpage").parent().addClass("active");
            $("#currentpage").parent().removeClass("active");
        }
    })

    /**
     * 加载日志列表
     * @param acceptBeginTime
     * @param acceptEndTime
     * @param appName
     * @param username
     * @param page
     */
    function loadLogTable(acceptBeginTime,acceptEndTime,appName,username,page){
        var logurl="";
        if(username!=null && username!=''){
            logurl="/connmonitor/"+acceptBeginTime+"/"+acceptEndTime+"/"+appName+"/list?username="+username+"&page="+page;
        }else{
            logurl="/connmonitor/"+acceptBeginTime+"/"+acceptEndTime+"/"+appName+"/list?page="+page;
        }
        $.ajax({
            type: 'POST',
            url: logurl,
            dataType: 'json',
            cache: false,
            async: true,
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                if (data && data.length > 0) {
                    var index = 1;
                    var parent = $("#table-body");
                    var template = $("tr[name=table-row-template]");

                    $(parent).empty();
                    data.forEach(function (entry) {
                        buildRow(template, parent, index++, entry);
                    })
                    $("#currentpage").html("当前页："+(monitorpage+1));
                }else{
                    $("#table-body").empty();
                    if(monitorpage!=0) {
                        monitorpage--;
                    }
                    $("#currentpage").html("当前页："+(monitorpage+1));
                }
            },
            error: function (data) {
            }
        });
    }


    /**
     * 创建日志行
     * @param template
     * @param parent
     * @param index
     * @param log_conn_pool
     */
    function buildRow(template, parent, index, log_conn_pool) {
        var row = $(template).clone();
        $(row).removeAttr("name");
        $(row).find("td[name=table-row-id]").text(index);
        $(row).find("td[name=table-row-traceId]").text(log_conn_pool.traceId);
        $(row).find("td[name=table-row-appName]").text(log_conn_pool.appName);
        $(row).find("td[name=table-row-poolName]").text(log_conn_pool.poolName);
        $(row).find("td[name=table-row-readonly]").text(log_conn_pool.isReadOnly);
        $(row).find("td[name=table-row-conntimeout]").text(log_conn_pool.connectionTimeout);
        $(row).find("td[name=table-row-idletimeout]").text(log_conn_pool.idleTimeout);
        $(row).find("td[name=table-row-jdbcUrl]").text(log_conn_pool.jdbcUrl);
        $(row).find("td[name=table-row-username]").text(log_conn_pool.dbuser);
        $(row).find("td[name=table-row-maxPoolSize]").text(log_conn_pool.maxPoolSize);
        $(row).find("td[name=table-row-minIdle]").text(log_conn_pool.minIdle);
        $(row).find("td[name=table-row-totalConns]").text(log_conn_pool.totalConnections);
        $(row).find("td[name=table-row-idleConns]").text(log_conn_pool.idleConnections);
        $(row).find("td[name=table-row-activeConns]").text(log_conn_pool.activeConnections);
        $(row).find("td[name=table-row-awaitingConns]").text(log_conn_pool.awaitingConnections);
        $(row).find("td[name=table-row-createTime]").text(new Date(log_conn_pool.createTime).format("yyyy-MM-dd hh:mm:ss"));
        $(row).find("td[name=table-row-acceptTime]").text(new Date(log_conn_pool.acceptTime).format("yyyy-MM-dd hh:mm:ss"));
        $(parent).append(row.show());
    }

    initAppList();
});
